#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
Create on May 2011

@author Wang Qiang
"""


import sys
import os
path = os.path.join(os.path.dirname(__file__), '..')
sys.path.append(path)

from QQWeiboAPI.qqAPI import QQAPI
from QQWeiboAPI import oauth
import unittest
import simplejson as json
import webbrowser


class OAuthTest(unittest.TestCase):
    """
    Test for the OAuth operation
    Get Requset Token
    Get Access Token
    """

    consumer_key = ''
    consumer_secret = ''
            
    def testConsumer(self):
        """test for loading consumer"""
        path = os.path.join(os.path.dirname(__file__), 'consumer.txt')
        f = open(path, 'r')
        consumerStr = f.read()
        f.close()
        consumer = json.loads(consumerStr)
        self.consumer_key = consumer['key']
        self.consumer_secret = consumer['secret']
        self.assertEqual(len(self.consumer_key), 32)
        self.assertEqual(len(self.consumer_secret), 32)

    def testAccessToken(self):
        """test for getting access token"""
        self.testConsumer()
        consumerToken = oauth.OAuthToken(self.consumer_key, \
                                         self.consumer_secret)
        testAPI = QQAPI(consumerToken)
        request_token = testAPI.get_request_token(oauth_callback='null')
        self.assertEqual(request_token.ret, 0)
        auth_url = 'https://open.t.qq.com/cgi-bin/authorize?oauth_token='\
                + request_token.data.oauth_token
        webbrowser.open_new_tab(auth_url)
        verifier = raw_input('PIN: ').strip()
        self.assertEqual(len(verifier), 6)
        requestToken = oauth.OAuthToken(request_token.data.oauth_token, \
                              request_token.data.oauth_token_secret)
        testAPI.access_token = requestToken
        access_token = testAPI.get_access_token(oauth_verifier=verifier)
        self.assertEqual(access_token.ret, 0)
        path = os.path.join(os.path.dirname(__file__), 'access_token.txt')
        f = open(path, 'w')
        f.write("{\n")
        f.write('     "key": "' + access_token.data.oauth_token + \
                '"' + ",\n")
        f.write('     "secret": "' + access_token.data.oauth_token_secret \
                + '"' + "\n")
        f.write("}")
        f.close()


if __name__ == '__main__':
    unittest.main()
